//
//  ConfigNetworkViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/11.
//

#import "ConfigNetworkViewController.h"

@interface ConfigNetworkViewController ()<PPBleStateInterface>
@property (weak, nonatomic) IBOutlet UITextField *ssidTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIButton *configBtn;

@property (nonatomic, strong) PPScaleManager *scaleManager;

@end

@implementation ConfigNetworkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Config Wifi";
    [self connectScale];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.scaleManager disconnect];
}

+ (instancetype)instance{
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ConfigNetworkViewController"];
}

- (IBAction)configBtnClick:(id)sender {
    LFWeakSelf(self)

    NSString *passWord = self.passwordTF.text;
    [self.scaleManager configNetWorkWithSSID:self.ssidTF.text password:passWord andSuccessHandler:^(BOOL isSuccess, NSString *sn) {
        if (isSuccess) {
            [weakself.scaleManager disconnect];
            [weakself bindDevice2UserBySN:sn];
        }else{
            [ProgressHud showText:sn];
        }
    }];
}

- (void)connectScale{
    UserModel *user = [IdentityManager manager].currentUser;
    PPUserModel *userModel = [[PPUserModel alloc] initWithUserHeight:user.userHeight gender:user.userGender age:user.userAge andUnit:user.userUnit];
    self.scaleManager = [[PPScaleManager alloc] initWithMacAddressList:@[self.device.deviceMac] filterDeviceNameArr:@[self.device.deviceName] andUserModel:userModel];
    self.scaleManager.stateInterface = self;
    [self.scaleManager startSearching];
}


- (void)monitorBluetoothWorkState:(PPBleWorkState)state{
    if (state == PPBleWorkStateConnected) {
        self.configBtn.enabled = YES;
    }else if (state == PPBleWorkStateDisconnected) {
        [self.scaleManager reStartSearching];
        self.configBtn.enabled = NO;
    }else{
        self.configBtn.enabled = NO;
    }
}

- (void)bindDevice2UserBySN:(NSString *)sn{
    LFWeakSelf(self)
    NSDictionary *parameters = @{@"sn" : sn,
                                 @"uid" : [IdentityManager manager].currentUser.userId
    };
    [[HttpRequest request] sendRequestWithHttpMethod:E_HTTP_REQUEST_METHOD_POST URLPath:@"/lefu/wifi/app/saveWifiGroup" parameters: parameters completionHandler:^(id  _Nonnull data, NSError * _Nonnull error) {
        [ProgressHud showText:@"bind success"];
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            weakself.device.deviceSN = sn;
            weakself.device.deviceSSID = weakself.ssidTF.text;
        }];
        [weakself.navigationController popViewControllerAnimated:YES];
    }];
}

@end
